package huang.com.android.searchmanagerdemo;

import android.app.SearchManager;
import android.content.Intent;
import android.provider.SearchRecentSuggestions;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class SearchResult extends AppCompatActivity implements View.OnClickListener {
    private TextView tvquery,tvdata;
    private Button btnsearch;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_manager_result);

        tvquery = (TextView) findViewById(R.id.tvquery);
        tvdata = (TextView) findViewById(R.id.tvdata);
        btnsearch = (Button) findViewById(R.id.btnSearch);
        doSearchQuery();
        btnsearch.setOnClickListener(this);
    }

    private void doSearchQuery() {
        final Intent intent = getIntent();

        String query = intent.getStringExtra(SearchManager.QUERY);
        tvquery.setText(query);

        SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
                SearchSuggestionSampleProvider.AuTHORITY,SearchSuggestionSampleProvider.MODE);

        suggestions.saveRecentQuery(query,null);
        if (Intent.ACTION_SEARCH.equals(intent.getAction())){

            Bundle bundled = intent.getBundleExtra(SearchManager.APP_DATA);
            if (bundled != null){
                String ttdata = bundled.getString("data");
                tvdata.setText(ttdata);
            }else {
                tvdata.setText("no data");
            }
        }

    }

    @Override
    public void onClick(View v) {
        onSearchRequested();
    }

    @Override
    public boolean onSearchRequested() {
        startSearch("onNewIntent",false,null,false);
        return true;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        String query = intent.getStringExtra(SearchManager.QUERY);
        tvquery.setText(query);

        SearchRecentSuggestions suggestions = new SearchRecentSuggestions(
                this,SearchSuggestionSampleProvider.AuTHORITY,SearchSuggestionSampleProvider.MODE
        );
        suggestions.saveRecentQuery(query,null);

        if (Intent.ACTION_SEARCH.equals(intent.getAction())){

            Bundle bundled = intent.getBundleExtra(SearchManager.APP_DATA);
            if (bundled != null){
                String ttdata = bundled.getString("data");
                tvdata.setText(ttdata);
            }else {
                tvdata.setText("no data");
            }
        }
    }
}
